<template>
	<view>
		<form>
			<view class="cu-form-group">
				<view class="title">素材名称</view>
				<input placeholder="请填写素材名称" name="input" v-model="material.name"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">素材描述</view>
				<input placeholder="素材描述" name="input" v-model="material.sucai_miaosu"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">可修改范围</view>
				<input placeholder="可修改范围" name="input" v-model="material.fangwei"></input>
			</view>
			
			<view class="cu-form-group">
				<view class="title">文件大小</view>
				<input placeholder="文件大小" name="input" v-model="material.size"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">收费金额</view>
				<input placeholder="收费金额" name="input" type="digit" v-model="material.qian"></input>
			</view>
			<view class="cu-form-group" @tap="toggleMaskLocation">
				<view class="title">获取分类</view>
				<view>
					<text>{{categoryValue}}</text>
					<text class="cuIcon-right text-gray"></text>
				</view>
			</view>

		</form>
		<view class="margin-top bg-white padding-bottom-sm">
			<view class="submin-img">
				<view class="cu-bar" >
					<view class="action">
						<text class="cuIcon-title text-orange "></text> 宣传图片
					</view>
					<view class="action">
						{{unloadImgs.length}}/{{imgMaxNum}}
					</view>
				</view>
				<view class="cu-form-group padding: 0;" >
					<view class="grid col-4 grid-square flex-sub">
						<view class="bg-img" v-for="(item,index) in unloadImgs" :key="index" :data-type="1" @tap="ViewImage" :data-url="unloadImgs[index]">
							<image :src="unloadImgs[index]" mode="aspectFill"></image>
							<view class="cu-tag bg-red" @tap.stop="DelNotUnloadImg" :data-type="0" :data-index="index">
								<text class='cuIcon-close'></text>
							</view>
						</view>
						<view class="solids" @tap="ChooseImage" v-if="unloadImgs.length<imgMaxNum">
							<text class='cuIcon-cameraadd'></text>
						</view>
					</view>
				</view>
			</view>
			
			<view class="submin-img padding-bottom">
				<view class="cu-bar" >
					<view class="action">
						<text class="cuIcon-title text-orange "></text> 视频素材
					</view>
					<view class="action">
						{{unloadVideo.length}}/{{videoMaxNum}}
					</view>
				</view>
				<view class="cu-form-group padding: 0;" >
					<view class="grid col-4 grid-square flex-sub">
						<view class="bg-img" v-for="(item,index) in unloadVideo" :key="index" :data-type="1" :data-url="unloadVideo[index]">
							<video class="video-data" :src="unloadVideo[index]" show-fullscreen-btn="true" object-fit="fill" ></video>
							<view class="cu-tag bg-red"  @tap.stop="DelNotUnloadImg" :data-type="1" :data-index="index">
								<text class='cuIcon-close'></text>
							</view>
						</view>
						<view class="solids" @tap="ChooseVideo" v-if="unloadVideo.length<videoMaxNum">
							<text class='cuIcon-cameraadd'></text>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<gk-city headtitle="请选择分类" mode="cityPicker" ref="cityPicker" @funcvalue="getpickerParentValue"
			:provincedata="provincedata"
		    :pickerSize="3"></gk-city>
		
		<view class="padding flex flex-direction">
			<button class="cu-btn bg-red lg" @tap="addSuCai">提交</button>
		</view>
	</view>
</template>

<script>
	import category from '@/pages/category/category.js';
	import uploadFile from '@/js_sdk/yushijie-ossutil/ossutil/uploadFile.js';
	export default {
		data() {
			return {
				imgMaxNum:1,
				videoMaxNum:4,
				unloadImgs:[] ,//要上传的图片(预览)
				unloadVideo:[] , //要上传的视频
				user : this.$store.state.user,
				material : {
					id : this.$moment.now().valueOf(),
					create_user: this.$store.state.user.id,
					name:"",
					sucai_miaosu:"",
					fangwei:"",
					size:"",
					// video_id:10001,
					dianbu_id: this.$store.state.user.dianbu_id,
					leixing:"视频",
					yinping:"www.baidu.com",
					fenbianlu:"1920*1071",
					bianhao: this.$moment.now().valueOf(),
					create_time: this.$moment.now(),
					ruanjian:"ps",
					urlJson: [],
					backImage : '',
					qian : '',
					// create_user :   this.$store.state.user.user_name // uni.getStorageSync("user").user_name
				},
				categoryValue:"请选择",
				provincedata:[{
					name:'请选择',
					categoryId:'',
					selfData:category.categoryData,
				}],
				
			};
		},
		onShow(){
					this.$store.commit('setMaterial',  this.material);
		},
		methods:{
			toggleMaskLocation(){
				this.$refs["cityPicker"].show();
			},
			getpickerParentValue(data){  //获取分类参数
				this.provincedata=data;
				let valueArr = [];
				for (let item of data) {
					valueArr.push(item.name);
				}
				this.categoryValue = valueArr.join('/');
			},
			ViewImage(e) {
				let that = this;
				let type = e.currentTarget.dataset.type;
				let imgs = [];
				for (let item of that.unloadImgs) {
					imgs.push(item);
				}
				uni.previewImage({
					urls: imgs,
					current: e.currentTarget.dataset.url
				});
			},
			ChooseImage() {//选择图片
				let that = this;
				uni.chooseImage({
					count: that.imgMaxNum, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (response) => {
						that.unloadImgs = response.tempFilePaths
					}
				});
			},
			ChooseVideo(){
				var that = this;
				uni.chooseVideo({
					count: this.videoMaxNum,
					sourceType: ['camera', 'album'],
					success: function (res) {
						console.log(res);
						if (that.unloadVideo != 0) {
							that.unloadVideo = that.unloadVideo.concat(res.tempFilePath)
						} else {
							that.unloadVideo.push(res.tempFilePath)
						}
					}
				});
			},
			DelNotUnloadImg(e){//删除未上传图片
				let type = e.currentTarget.dataset.type; //0：图片 1：视频
				uni.showModal({
					title: '提示',
					content: '确定要删除这张图片吗？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							if(type == 0){
								this.unloadImgs.splice(e.currentTarget.dataset.index, 1)
							}else{
								this.unloadVideo.splice(e.currentTarget.dataset.index, 1)
							}
						}
					}
				})
			},
			unloadImg(){ //API https://uniapp.dcloud.io/api/request/network-file?id=uploadfile
				let that = this;
				/* uni.uploadFile({
					url: 'https://www.example.com/upload', //仅为示例，非真实的接口地址
					filePath: that.unloadImgs[0],
					name: 'file',
					formData: {
						'user': 'test'
					},
					success: (uploadFileRes) => {
						console.log(uploadFileRes.data);
					}
				}); */
			},
			unloadVideos(){ //API https://uniapp.dcloud.io/api/request/network-file?id=uploadfile
				let that = this;
				let videos = this.unloadVideo.map((value,index) => {
					return {
						name:'file',
						uri: value
					}
				})
				// uni.uploadFile({
				// 	url: 'https://www.example.com/upload', //仅为示例，非真实的接口地址
				// 	files: videos,
				// 	formData: {
				// 		'user': 'test'
				// 	},
				// 	success: (uploadFileRes) => {
				// 		console.log(uploadFileRes.data);
				// 	}
				// });
			},
			addSuCai: async function() {
					if( this.material.create_user){
						// 先添加素材.  updateDate是素材里面的json数组字段.
						let flag = new Date().getTime() + Math.floor(Math.random() * 150)
						let imageUrl = `shiping/imageUrl/${this.$store.state.user.id}-${flag}.png`;
						// unloadImgs:[] ,//要上传的图片(预览)
						this.material.backImage = uploadFile(this.unloadImgs[0] , imageUrl);
						// unloadVideo:[] , //要上传的视频
						this.material.leixing = this.categoryValue;
						for (var i = 0; i < this.unloadVideo.length; i++) {
							let videoUrl = `shiping/${this.$store.state.user.id}-${flag}-${i}.mp4`;
							let uploadUrl = uploadFile(this.unloadVideo[i] , videoUrl);
							
							this.material.urlJson.push({
								'upload_percent' : uploadUrl
							});
						}
						//
						let sp_material = this.$httpApi.insert("Sp_material" ,this.material);
						this.switchTab('/pages/index/index' , '添加素材成功.');
					}else{
						this.showToast('请先登录后上传.');
					}
			}
		}
	}
</script>

<style lang="scss">
.cu-form-group{
	.title{
		min-width: 180upx;
		padding: 0;
	}
}
.grid.grid-square>uni-view.bg-img uni-image{
	width: 100%;
	height: 100%;
	position: absolute;
}
.submin-img{
	.video-data{
		width: 100%;
		height: 160upx;
	}
	.solids{
		border-radius: 35upx;
		overflow: initial;
		margin-bottom: 0px;
	}

}

</style>
